package com.ysh.xiaomi.web.servelt;

import com.ysh.xiaomi.pojo.CartDto;
import com.ysh.xiaomi.pojo.TbGoods;
import com.ysh.xiaomi.pojo.TbUser;
import com.ysh.xiaomi.service.CartService;
import com.ysh.xiaomi.service.impl.CartServiceImpl;
import com.ysh.xiaomi.utils.StringConstans;
import com.ysh.xiaomi.utils.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 袁胜虎 on 2022/8/18 17:09
 */
public class CartServlet {
    CartService cartService = new CartServiceImpl();

    public String create(HttpServletRequest request, HttpServletResponse response) {
        //我们要把什么商品加入到购物车,加入到哪个用户的购物车
        //我们要求必须传递一个id的参数代表商品的id
        //要求必须登录,从登录保存的数据中可以获取到用户的id
        // 商品id
        String id = request.getParameter("id");
        if (StringUtils.isEmpty(id)){
            //如果没有传递id
            return StringConstans.REDIRECT + "/index.jsp";
        }
        //      把id转成数字
        long goodId = Long.parseLong(id);
        //获取登录用户
        TbUser user = (TbUser)request.getSession().getAttribute("user");
        //获取到用户id
        Long userId = user.getId();
        cartService.upsert(goodId,userId);
        //注意我们要冲顶下过去,因为我们现在是在执行一个非幂等性的操作,但是我们需要幂等性的结果
        return StringConstans.REDIRECT + "/cartSuccess.jsp";
    }
    public String show(HttpServletRequest request,HttpServletResponse response ){
        //获取到当前登录的用户
        TbUser user = (TbUser) request.getSession().getAttribute("user");
        Long userId = user.getId();
        CartDto cartDto = cartService.findCartGoodsByUserId(userId);
        //将数据保存到请求中
        request.getSession().setAttribute("cart",cartDto);
        //先随便返回一个页面
        return StringConstans.REDIRECT + "/cart.jsp";
    }
    public String clear(HttpServletRequest request, HttpServletResponse response){
        TbUser User = (TbUser) request.getSession().getAttribute("user");//获取当前登录用户
        Long userId = User.getId();
        try {
            cartService.clearCart(userId); ;
        } catch (Exception e) {
            e.printStackTrace();
        }
        CartDto cartGoodsByUserId = cartService.findCartGoodsByUserId(userId);//获取到当前用户的购物车数据
        request.getSession().setAttribute("cart", cartGoodsByUserId);
        return StringConstans.REDIRECT + "/cart.jsp";
    }
    //删除单个订单
    public String del(HttpServletRequest request, HttpServletResponse response){
        TbUser User = (TbUser) request.getSession().getAttribute("user");//获取当前登录用户
        return null;
    }
}